from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
# 移除JWT导入，使用Flask-Login
from models import Comment, Post
from extensions import db
from sqlalchemy import desc
from datetime import datetime
import logging

logger = logging.getLogger('Personal_Blog_System')

# 创建评论API蓝图
comment_api = Blueprint('comment_api', __name__, url_prefix='/api/comments')

@comment_api.route('/', methods=['GET'])
def get_comments():
    """获取评论列表"""
    try:
        post_id = request.args.get('post_id', type=int)
        status = request.args.get('status', 'approved')
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        
        # 构建查询
        query = Comment.query
        
        if post_id:
            query = query.filter_by(post_id=post_id)
        
        if status:
            query = query.filter_by(status=status)
        
        # 排序和分页
        comments = query.order_by(desc(Comment.created_at)).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        # 构建响应数据
        comments_data = []
        for comment in comments.items:
            comment_data = {
                'id': comment.id,
                'post_id': comment.post_id,
                'post_title': comment.post.title if comment.post else None,
                'author_name': comment.author_name,
                'author_email': comment.author_email,
                'author_website': comment.author_website,
                'content': comment.content,
                'status': comment.status,
                'created_at': comment.created_at.isoformat(),
                'updated_at': comment.updated_at.isoformat()
            }
            
            comments_data.append(comment_data)
        
        return jsonify({
            'success': True,
            'data': {
                'comments': comments_data,
                'pagination': {
                    'page': comments.page,
                    'pages': comments.pages,
                    'per_page': comments.per_page,
                    'total': comments.total,
                    'has_next': comments.has_next,
                    'has_prev': comments.has_prev
                }
            }
        })
        
    except Exception as e:
        logger.error(f"获取评论列表失败: {str(e)}")
        return jsonify({'success': False, 'message': '获取评论列表失败'}), 500

@comment_api.route('/<int:comment_id>', methods=['GET'])
def get_comment(comment_id):
    """获取单个评论"""
    try:
        comment = Comment.query.get_or_404(comment_id)
        
        comment_data = {
            'id': comment.id,
            'post_id': comment.post_id,
            'post_title': comment.post.title if comment.post else None,
            'author_name': comment.author_name,
            'author_email': comment.author_email,
            'author_website': comment.author_website,
            'content': comment.content,
            'parent_id': comment.parent_id,
            'status': comment.status,
            'ip_address': comment.ip_address,
            'user_agent': comment.user_agent,
            'created_at': comment.created_at.isoformat(),
            'updated_at': comment.updated_at.isoformat()
        }
        
        return jsonify({'success': True, 'data': comment_data})
        
    except Exception as e:
        logger.error(f"获取评论失败: {str(e)}")
        return jsonify({'success': False, 'message': '获取评论失败'}), 500

@comment_api.route('/', methods=['POST'])
def create_comment():
    """创建评论"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['post_id', 'author_name', 'author_email', 'content']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'success': False, 'message': f'{field}是必填字段'}), 400
        
        # 获取文章ID
        post_id = data['post_id']
        
        # 检查文章是否存在且允许评论
        post = Post.query.get(post_id)
        if not post:
            return jsonify({'success': False, 'message': '文章不存在'}), 404
        
        if not post.allow_comments:
            return jsonify({'success': False, 'message': '该文章不允许评论'}), 400
        
        # 创建评论
        comment = Comment(
            post_id=post_id,
            author_name=data['author_name'],
            author_email=data['author_email'],
            author_website=data.get('author_website'),
            content=data['content'],
            parent_id=None,  # 移除回复功能，parent_id始终为None
            status='pending',  # 新评论默认为待审核
            ip_address=request.remote_addr,
            user_agent=request.headers.get('User-Agent')
        )
        
        db.session.add(comment)
        db.session.commit()
        
        # 更新文章评论数
        post.comment_count = Comment.query.filter_by(post_id=post.id, status='approved').count()
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '评论提交成功，等待审核',
            'data': {'id': comment.id}
        }), 201
        
    except Exception as e:
        logger.error(f"创建评论失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '创建评论失败'}), 500

@comment_api.route('/<int:comment_id>', methods=['PUT'])
@login_required
def update_comment(comment_id):
    """更新评论状态"""
    try:
        comment = Comment.query.get_or_404(comment_id)
        data = request.get_json()
        
        # 只允许更新状态
        if 'status' in data:
            comment.status = data['status']
            
            # 如果状态改为approved，更新文章评论数
            if data['status'] == 'approved':
                post = comment.post
                post.comment_count = Comment.query.filter_by(post_id=post.id, status='approved').count()
        
        db.session.commit()
        
        return jsonify({'success': True, 'message': '评论状态更新成功'})
        
    except Exception as e:
        logger.error(f"更新评论失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '更新评论失败'}), 500

@comment_api.route('/<int:comment_id>', methods=['DELETE'])
@login_required
def delete_comment(comment_id):
    """删除评论"""
    try:
        comment = Comment.query.get_or_404(comment_id)
        post = comment.post
        
        # 删除评论（级联删除回复）
        db.session.delete(comment)
        db.session.commit()
        
        # 更新文章评论数
        if post:
            post.comment_count = Comment.query.filter_by(post_id=post.id, status='approved').count()
            db.session.commit()
        
        return jsonify({'success': True, 'message': '评论删除成功'})
        
    except Exception as e:
        logger.error(f"删除评论失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '删除评论失败'}), 500

@comment_api.route('/<int:comment_id>/approve', methods=['POST'])
@login_required
def approve_comment(comment_id):
    """审核通过评论"""
    try:
        comment = Comment.query.get_or_404(comment_id)
        comment.status = 'approved'
        db.session.commit()
        
        # 更新文章评论数
        post = comment.post
        post.comment_count = Comment.query.filter_by(post_id=post.id, status='approved').count()
        db.session.commit()
        
        return jsonify({'success': True, 'message': '评论审核通过'})
        
    except Exception as e:
        logger.error(f"审核评论失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '审核评论失败'}), 500

@comment_api.route('/<int:comment_id>/reject', methods=['POST'])
@login_required
def reject_comment(comment_id):
    """拒绝评论"""
    try:
        comment = Comment.query.get_or_404(comment_id)
        comment.status = 'rejected'
        db.session.commit()
        
        return jsonify({'success': True, 'message': '评论已拒绝'})
        
    except Exception as e:
        logger.error(f"拒绝评论失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '拒绝评论失败'}), 500

@comment_api.route('/batch-approve', methods=['POST'])
@login_required
def batch_approve_comments():
    """批量审核通过评论"""
    try:
        data = request.get_json()
        comment_ids = data.get('ids', [])
        
        if not comment_ids:
            return jsonify({'success': False, 'message': '请选择要操作的评论'}), 400
        
        # 批量更新评论状态
        comments = Comment.query.filter(Comment.id.in_(comment_ids)).all()
        for comment in comments:
            comment.status = 'approved'
        
        db.session.commit()
        
        # 更新相关文章的评论数
        post_ids = set(comment.post_id for comment in comments if comment.post)
        for post_id in post_ids:
            post = Post.query.get(post_id)
            if post:
                post.comment_count = Comment.query.filter_by(post_id=post_id, status='approved').count()
        
        db.session.commit()
        
        return jsonify({'success': True, 'message': f'已通过 {len(comments)} 条评论'})
        
    except Exception as e:
        logger.error(f"批量审核评论失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '批量审核失败'}), 500

@comment_api.route('/batch-reject', methods=['POST'])
@login_required
def batch_reject_comments():
    """批量拒绝评论"""
    try:
        data = request.get_json()
        comment_ids = data.get('ids', [])
        
        if not comment_ids:
            return jsonify({'success': False, 'message': '请选择要操作的评论'}), 400
        
        # 批量更新评论状态
        comments = Comment.query.filter(Comment.id.in_(comment_ids)).all()
        for comment in comments:
            comment.status = 'rejected'
        
        db.session.commit()
        
        # 更新相关文章的评论数
        post_ids = set(comment.post_id for comment in comments if comment.post)
        for post_id in post_ids:
            post = Post.query.get(post_id)
            if post:
                post.comment_count = Comment.query.filter_by(post_id=post_id, status='approved').count()
        
        db.session.commit()
        
        return jsonify({'success': True, 'message': f'已拒绝 {len(comments)} 条评论'})
        
    except Exception as e:
        logger.error(f"批量拒绝评论失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '批量拒绝失败'}), 500

@comment_api.route('/batch-delete', methods=['POST'])
@login_required
def batch_delete_comments():
    """批量删除评论"""
    try:
        data = request.get_json()
        comment_ids = data.get('ids', [])
        
        if not comment_ids:
            return jsonify({'success': False, 'message': '请选择要操作的评论'}), 400
        
        # 批量删除评论
        comments = Comment.query.filter(Comment.id.in_(comment_ids)).all()
        post_ids = set(comment.post_id for comment in comments if comment.post)
        
        for comment in comments:
            db.session.delete(comment)
        
        db.session.commit()
        
        # 更新相关文章的评论数
        for post_id in post_ids:
            post = Post.query.get(post_id)
            if post:
                post.comment_count = Comment.query.filter_by(post_id=post_id, status='approved').count()
        
        db.session.commit()
        
        return jsonify({'success': True, 'message': f'已删除 {len(comments)} 条评论'})
        
    except Exception as e:
        logger.error(f"批量删除评论失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '批量删除失败'}), 500